package com.guiassysdesigners.service.impl;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.jws.WebService;
import javax.print.attribute.standard.Severity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.guiassysdesigners.dao.SuggestionDao;
import com.guiassysdesigners.model.Suggestion;
import com.guiassysdesigners.model.User;
import com.guiassysdesigners.service.FormValidationException;
import com.guiassysdesigners.service.SuggestionManager;
import com.guiassysdesigners.service.UserExistsException;

/**
 * Implementation of SuggestionManager interface.
 * 
 * @author <a href="mailto:guiassys@gmail.com">Guilherme Assis</a>
 */
@Service("suggestionManager")
@WebService(serviceName = "SuggestionService", endpointInterface = "com.guiassysdesigners.service.SuggestionService")
public class SuggestionManagerImpl extends GenericManagerImpl<Suggestion, Long>
		implements SuggestionManager, SuggestionService {

	private SuggestionDao suggestionDao;

	@Autowired
	public void setSuggestionDao(SuggestionDao suggestionDao) {
		this.dao = suggestionDao;
		this.suggestionDao = suggestionDao;

	}

	/**
	 * {@inheritDoc}
	 */
	public Suggestion getSuggestion(String suggestionId) {
		return suggestionDao.get(new Long(suggestionId));
	}

	/**
	 * {@inheritDoc}
	 */
	public List<Suggestion> getListSuggestion() {
		return suggestionDao.getAllDistinct();
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @throws Exception
	 */
	public Suggestion saveSuggestion(Suggestion suggestion) throws FormValidationException{

		// recupera o usuário corrente
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		User currentUser = (User) auth.getPrincipal();
		
		if(null == suggestion.getId()){
			suggestion.setUser(currentUser);
		}
		
		//valida formulário
		ValidaFormularioSaveSuggestion(suggestion);
		
		//formata objeto antes da persistencia
		FormatFormSuggestion(suggestion);

		try {
			return suggestionDao.save(suggestion);
		} catch (Exception e) {
			e.printStackTrace();
			log.warn(e.getMessage());
			return null;
		}
	}

	/**
	 * Formata o formulário de sugestão antes de persistir dados no banco de
	 * dados.
	 * 
	 * @param suggestion
	 */
	private void FormatFormSuggestion(Suggestion suggestion) {
		suggestion.setTitle(suggestion.getTitle().trim());
		suggestion.setDescription(suggestion.getDescription().trim());
	}

	/**
	 * Metodo utilizado para validar o formulário de sugestões.
	 * @param suggestion
	 * @throws FormValidationException
	 */
	private void ValidaFormularioSaveSuggestion(Suggestion suggestion)
			throws FormValidationException {
		//verifica se todos os campos do formulário estão preenchidos corretamente
		if(null == suggestion.getTitle() || "".equals(suggestion.getTitle().trim())){  
			throw new FormValidationException("errors.required","suggestion.title");
		}
		//verifica se todos os campos do formulário estão preenchidos corretamente
		if(null == suggestion.getDescription() || "".equals(suggestion.getDescription().trim())){  
			throw new FormValidationException("errors.required","suggestion.description");
		}
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @throws Exception
	 */
	public void removeSuggestion(Suggestion suggestion) {
		log.debug("removing suggestion: " + suggestion);
		suggestionDao.remove(suggestion);

	}

	/**
	 * {@inheritDoc}
	 * 
	 * @throws Exception
	 */
	public void removeSuggestion(String suggestionId) {
		log.debug("removing suggestion: " + suggestionId);
		suggestionDao.remove(new Long(suggestionId));

	}

	/**
	 * {@inheritDoc}
	 * 
	 * @throws Exception
	 */
	public List<Suggestion> search(String searchTerm) {
		return super.search(searchTerm, Suggestion.class);
	}

}
